package com.clp.protocol.iec104.apdu.asdu.infoobj.infoelem;

import com.clp.protocol.iec104.definition.Tm;
import com.clp.protocol.iec104.definition.TypeTag;
import com.clp.protocol.core.pdu.nbytepdu.BaseNBytePduClip;
import com.clp.protocol.core.pdu.ByteToStringFormat;
import com.clp.protocol.core.utils.ByteUtil;
import io.netty.buffer.ByteBuf;
import lombok.Getter;

import java.util.Objects;
import java.util.function.Consumer;

/**
 * 遥测 归一化值 信息元素内容
 */
@Getter
public class M_ME_NA_1_InfoElem extends TmInfoElem {
    /**
     * 归一化值用整型表示
     */
    private int intVal;

    public M_ME_NA_1_InfoElem() {
        this(-1);
    }

    public M_ME_NA_1_InfoElem(int intVal) {
        super(TypeTag.M_ME_NA_1);
        this.intVal = intVal;
    }

    @Override
    public M_ME_NA_1_InfoElem refreshFrom(ByteBuf buf) {
        byte[] bytes = new byte[typeTag().getInfoElemBytesLen()];
        buf.readBytes(bytes);
        this.intVal = ByteUtil.bytes2ToIntLE(bytes);
        return this;
    }

    @Override
    public boolean isValid() {
        return intVal >= 0 && intVal <= 0xFFFF;
    }

    @Override
    public void writeBytesTo(ByteBuf buf) {
        // TODO 暂不处理
        buf.writeBytes(new byte[]{0x00, 0x00});
    }

    @Override
    public void writeFormattedByteStringsTo(StringBuilder sb, String frameClipBytesSeparator, String byteSeparator, ByteToStringFormat byteFormat) {
        byte[] bytes = ByteUtil.intToBytes2LE(intVal);
        sb.append(byteFormat.format(bytes[0]));
        for (int i = 1; i < bytes.length; i++) {
            sb.append(byteSeparator).append(byteFormat.format(bytes[i]));
        }
    }

    @Override
    public void writeSimpleDescriptionTo(StringBuilder sb) {
        sb.append(intVal);
    }

    @Override
    public void writeDetailDescriptionTo(StringBuilder sb) {
        sb.append("归一化值（整型表示）：").append(intVal);
    }

    @Override
    public Tm.Type getTmType() {
        return Tm.Type.NORMALIZE;
    }

    @Override
    public Number getNumberVal() {
        return intVal;
    }

    @Override
    protected void forEachOneLevelChild(Consumer<BaseNBytePduClip<?>> consumer) {
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        M_ME_NA_1_InfoElem that = (M_ME_NA_1_InfoElem) o;
        return intVal == that.intVal;
    }

    @Override
    public int hashCode() {
        return Objects.hash(intVal);
    }
}
